package com.dst.smart.dialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.dst.smart.R;
import com.dst.smart.app.MainActivity;
import com.dst.smart.constant.Constants;
import com.dst.smart.socket.info.ISocketCode;

import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

//ȷ����ʾ��
public class DownServiceAlert extends Dialog {

	private Activity context;
	private TextView countText;
	private TextView leftText;
	ProgressBar progressBar;
	int indexValue = 0;
	private static final int DOWN_UPDATE = 1;
	private static final int DOWN_OVER = 2;
	private int progress;
	String ToID = "";
	int tempCount = 0;

	public DownServiceAlert(Activity context, String toID) {
		super(context, R.style.MyDialog);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.alert_down_verify);
		this.context = context;
		this.ToID = toID;
		countText = (TextView) findViewById(R.id.countTxt);
		leftText = (TextView) findViewById(R.id.leftTxt);
		progressBar = (ProgressBar) findViewById(R.id.proBar);

		downAppFile(Constants.downServicePath + Constants.appServiceName);
	}

	private String cmd_install = "pm install -r ";
	String apkLocation = Environment.getExternalStorageDirectory().toString()
			+ "/";
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				progressBar.setProgress(progress);
				Log.e("pro", progress + "");
				if (tempCount != progress) {
					tempCount = progress;
					String result = ISocketCode.setDownApk("" + progress, ToID);
					MainActivity.activity.sendCode(result);
				}
				break;
			case DOWN_OVER:
				String result = ISocketCode.setDownApk("" + 100, ToID);
				MainActivity.activity.sendCode(result);
				try {
					MainActivity.playSound(0, "AIUI服务更新成功，正在重启设备");
					Thread.sleep(1000);
					String cmd = cmd_install + apkLocation
							+ Constants.appServiceName;
					Intent intent = new Intent(
							"com.iflytek.aiuilauncher.action.CMD_LINE");
					intent.putExtra("cmd", cmd);
					MainActivity.activity.sendBroadcast(intent);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				break;
			default:
				break;
			}
		};
	};

	protected void downAppFile(final String url) {
		// pBar.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					Log.isLoggable("DownTag", (int) length);
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is == null) {
						throw new RuntimeException("isStream is null");
					}
					File file = new File(
							Environment.getExternalStorageDirectory(),
							Constants.appServiceName);
					fileOutputStream = new FileOutputStream(file);
					byte[] buf = new byte[1024];
					int count = 0;
					int ch = -1;
					do {
						ch = is.read(buf);
						count += ch;
						progress = (int) (((float) count / length) * 100);
						// 更新进度
						mHandler.sendEmptyMessage(DOWN_UPDATE);
						if (ch <= 0) {
							// 下载完成通知安装
							mHandler.sendEmptyMessage(DOWN_OVER);
							break;
						}
						fileOutputStream.write(buf, 0, ch);
					} while (true);
					is.close();
					fileOutputStream.close();

				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

}
